/*
 * Copyright 2008-2009 Daniel Cachapa <cachapa@gmail.com>
 * 
 * This program is distributed under the terms of the GNU General Public Licence Version 3
 * The licence can be read in its entirety in the LICENSE.txt file accompaning this source code,
 * or at: http://www.gnu.org/copyleft/gpl.html
 * 
 * This file is part of WeightWatch.
 *
 * WeightWatch is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * WeightWatch is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the WeightWatch source code. If not, see
 * <http://www.gnu.org/licenses/>.
 */

package net.cachapa.weightwatch.ui;

import com.sun.lwuit.Command;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.List;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BoxLayout;
import net.cachapa.weightwatch.util.HttpConnector;
import net.cachapa.weightwatch.util.L;
import net.cachapa.weightwatch.util.StringTokenizer;

public class UpdateForm extends Form implements ActionListener {

	Application application;
	private final static String JAD_URL = "http://cachapa.net/weightwatch/WeightWatch.jad";
	private HttpConnector http;
	private Label latestLabel;
	private Label sizeLabel;
	private Command updateCommand;
	private Command backCommand;
	private String runningVersion;
	private String latestVersion;
	private String jarSize;
	private Label availabilityLabel;
	private List changeList;

	public UpdateForm(Application application) {
		this.application = application;
		this.setTitle("update_title");
		this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));

		this.runningVersion = application.getAppProperty("MIDlet-Version");
		this.latestVersion = runningVersion;

		http = new HttpConnector(JAD_URL);
		http.setActionListener(this);

		this.addComponent(new Label(L.l("update_current") + " v" + runningVersion));

		availabilityLabel = new Label("");
		this.addComponent(availabilityLabel);

		latestLabel = new Label("");
		this.addComponent(latestLabel);

		sizeLabel = new Label("");
		this.addComponent(sizeLabel);
		
//		changeList = new List();
//		this.addComponent(changeList);
		
		updateCommand = new Command("update", 1);
		backCommand = new Command("back", 2);
		this.addCommand(updateCommand);
		this.addCommand(backCommand);
		this.setBackCommand(backCommand);
		this.setCommandListener(this);
	}

	public void show() {
		availabilityLabel.setText("(" + L.l("update_checking") + ")");
		latestLabel.setText(" ");
		sizeLabel.setText(" ");
		this.removeCommand(updateCommand);
		super.show();
		http.get();
	}

	public void actionPerformed(ActionEvent ae) {
		Object source = ae.getSource();
		if (source == http) {
			if (ae.getKeyEvent() == HttpConnector.RESULT_SUCCESS) {
				String jad = http.getResult();
				interpretJad(jad);
				if (runningVersion.compareTo(latestVersion) != 0) {
					availabilityLabel.setText(L.l("update_available"));
					latestLabel.setText(L.l("update_latest") + " v" + latestVersion);
					sizeLabel.setText(L.l("update_size") + ": " + jarSize + " KB");
					this.addCommand(updateCommand);
				} else {
					availabilityLabel.setText(L.l("update_noupdates"));
				}
			} else {
				availabilityLabel.setText("Connection error: " + http.getErrorMsg());
			}
		}
		
		else if (source == updateCommand) {
			boolean result = Dialog.show("update_title", "update_closemessage",
					Dialog.TYPE_INFO ,null, "ok", "cancel");
			if (result) {
				try {
					application.platformRequest(JAD_URL);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				application.performAction(Application.QUIT);
			}
		}
		
		else if (source == backCommand) {
			application.performAction(Application.SHOW_PREFERENCES_FORM);
		}
	}

	private void interpretJad(String jad) {
		StringTokenizer jadTokenizer = new StringTokenizer(jad, "\n");
		String jadToken, key, value;
		StringTokenizer lineTokenizer;
		while (jadTokenizer.hasMoreElements()) {
			jadToken = jadTokenizer.nextToken();
			lineTokenizer = new StringTokenizer(jadToken, ": ");
			key = lineTokenizer.nextToken();
			value = lineTokenizer.nextToken();
			if (key.toLowerCase().compareTo("MIDlet-Version".toLowerCase()) == 0) {
				latestVersion = value.trim();
			}
			else if (key.toLowerCase().compareTo("MIDlet-Jar-Size".toLowerCase()) == 0) {
				double realSize = Double.parseDouble(value) / 1024;
				jarSize = String.valueOf(Math.ceil(realSize * 10) / 10);
			}
			else if (key.toLowerCase().compareTo("MIDlet-Description".toLowerCase()) == 0) {
//				parseChangeLog(value);
			}
		}
	}

//	private void parseChangeLog(String changeLog) {
//		StringTokenizer logTokenizer = new StringTokenizer(changeLog, ";");
//		String change;
//		while (logTokenizer.hasMoreElements()) {
//			change = logTokenizer.nextToken();
//			changeList.addItem(change);
//		}
//	}
}
